Solving Equations
In this lesson, we will learn about solving different types of equations numerically and symbolically.
SymPy has equation solvers that can handle linear and non-linear algebraic equations as well as linear and non-linear multivariate equations. Depending upon the input equation, the answer returned can be symbolic or numeric. The most commonly used one is solve(). It uses the following syntax:
solve(f(x), x)
The output type of solve() varies with input, sometimes it returns a Python list and sometimes a Python dictionary. Usually, for single variable equations, it returns a list and for multivariable equations, it returns a dictionary.
Let’s explore different cases in the examples below:
Solving for a single variable#
Single solution#
Let’s solve the following equation that has a single solution:
The solve() function returns a list with the only solution.
The solve() function returns a list with all the solutions. Let’s solve an equation with complex roots:
The solve() function returns a list with all the solutions, which are complex numbers.
Interval solution#
Using SymPy, we can also find a solution for an interval. All we have to do is provide the interval alongside the equation
solve(f(x) > a, x)
where > a is the interval. Let’s see an example of interval solution:
In the code above (lines 10 and 11), we have computed the values of in the interval and respectively.
Trigonometric equations#
Using the SymPy module, we can solve trigonometric equations as well. Let’s solve the following equation in SymPy:
Solutions are in the range .
Solving systems of equations#
SymPy solve() is not just limited to solving a single variable equation, it can also solve a system of multivariable equations. This system of equations is to be in a list as the first argument of solve() and the variables will be in a list as the second argument of solve():
solve([eq1, eq2,...eqN], [x1, x2, x3,...xN])
Let’s solve the following system of equations:
Notice that the type of the
solis a dictionary where each variable is a key to its corresponding value.
Symbolic solution#
All the equations that we have solved can be solved with arbitrary coefficients as well. This technique is useful when optimizing systems. See the example below:
The solution that we get from these equations is in the form of a, b and c.
In the next lesson, we will learn about solving ordinary differential equations.
Series Expansion
Ordinary Differential Equations